package com.gzhryc.shared_device.oem.h5.mng.controllers.agent;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.jdbc.utils.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.models.AgentRelationCount;
import com.gzhryc.shared_device.oem.code.agent.dao.models.RelationUserDeviceCount;
import com.gzhryc.shared_device.oem.code.agent.dao.models.RelationUserFuncModelCount;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationDeviceService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationDeviceSearch;
import com.gzhryc.shared_device.oem.code.agent.services.dto.UserKeySearch;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.dao.models.UserProfitPlaceCount;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.agent.AgentRelationData;
import com.gzhryc.shared_device.oem.h5.mng.dto.agent.AgentRelationPlace;
import com.gzhryc.shared_device.oem.h5.mng.dto.agent.AgentRelationUser;

public class AgentRelationController {

    @Route(value = {"/agent/relation/list.html"})
    public String list(HttpServletRequest request) {
        return "/agent/relation/list.html";
    }

    @Route(value = "/agent/relation/list.data")
    public ListResult<AgentRelationData> listData(HttpServletRequest request) {
        ListResult<AgentRelationData> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        UserKeySearch search = WebUtils.getParameter(request,UserKeySearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(AgentRelationService.self().countRelationCount(search));
        List<AgentRelationCount> agentRelationCountList = AgentRelationService.self().findRelationCount(search,pageNo, pageLimit);
        if (agentRelationCountList != null && agentRelationCountList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());

            List<Long> userIds = new ArrayList<>();
            for (AgentRelationCount relationCount : agentRelationCountList) {
                userIds.add(relationCount.getUserId());
            }

            List<Agent> agentList = AgentService.self().findJoinByUserIds(userIds);
            List<User> userList = UserService.self().findByUserIds(userIds);

            for (AgentRelationCount relationCount : agentRelationCountList) {
                AgentRelationData item = new AgentRelationData();
                item.setUserId(relationCount.getUserId());
                item.setName("未知用户");
                item.setRelationUserCount(relationCount.getRelationUserCount());
                if (userList != null && userList.size() > 0) {
                    for (User user : userList) {
                        if (user.getId().equals(item.getUserId())) {
                            item.setName(user.getName());
                            item.setPhone(user.getPhone());
                            item.setCreateDate(user.getCreateDate());
                            break;
                        }
                    }
                }
                if (agentList != null && agentList.size() > 0) {
                    for (Agent agent : agentList) {
                        if (agent.getUserId().equals(item.getUserId())) {
                            item.setLevel(agent.getLevel());
                            item.setLevelName(agent.getLevelName());
                            break;
                        }
                    }
                }
                result.getBody().getData().add(item);
            }
        }
        return result;
    }

    @Route(value = {"/agent/relation/info.html"})
    public String info(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request, "userId");
        User user = UserService.self().getById(userId);
        WebUtils.setAttribute(request, user);
        return "/agent/relation/info.html";
    }

    @Route(value = { "/agent/relation/refresh.do" })
    public AjaxResult doRefresh(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"刷新失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        try {
            AgentRelationService.self().refresh(userId);
            result.setCode(DtoConstants.SUCCESS,null);
        } catch (Exception e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = "/agent/relation/user/list.data")
    public ListResult<AgentRelationUser> userListData(HttpServletRequest request) {
        ListResult<AgentRelationUser> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(AgentRelationService.self().countJoinByUserId(userId));
        List<AgentRelation> data = AgentRelationService.self().findJoinByUserId(userId,pageNo,pageLimit);
        if(data != null && data.size() > 0) {
            result.getBody().setData(new ArrayList<>());
            List<Long> relationUserIds = new ArrayList<>();
            for(AgentRelation agentRelation : data){
                relationUserIds.add(agentRelation.getRelationUserId());
            }

            List<RelationUserDeviceCount> userDeviceCountList = AgentRelationDeviceService.self()
                    .findDeviceCountByUserKeys(userId,relationUserIds);

            List<UserProfitPlaceCount> placeCountList = PlaceProfitUserService.self().findPlaceCountByUserKeys(userId
                    ,relationUserIds);

            List<RelationUserFuncModelCount> funcModelCountList = AgentRelationFuncModelService.self().findFuncModelCountByUserKeys(userId,relationUserIds);

            for(AgentRelation agentRelation : data){
                AgentRelationUser item = ClassTools.copy(new AgentRelationUser(),agentRelation);
                if(userDeviceCountList != null && userDeviceCountList.size() > 0){
                    for(RelationUserDeviceCount userDeviceCount : userDeviceCountList){
                        if(item.getRelationUserId().equals(userDeviceCount.getRelationUserId())){
                            item.setDeviceCount(userDeviceCount.getDeviceCount());
                            break;
                        }
                    }
                }
                if(placeCountList != null && placeCountList.size() > 0){
                    for(UserProfitPlaceCount profitPlaceCount : placeCountList){
                        if(item.getRelationUserId().equals(profitPlaceCount.getUserId())){
                            item.setPlaceCount(profitPlaceCount.getPlaceCount());
                            break;
                        }
                    }
                }
                if(funcModelCountList != null && funcModelCountList.size() > 0){
                    for(RelationUserFuncModelCount userProfitPlaceCount : funcModelCountList){
                        if(item.getRelationUserId().equals(userProfitPlaceCount.getRelationUserId())){
                            item.setFuncModelCount(userProfitPlaceCount.getFuncModelCount());
                            break;
                        }
                    }
                }
                result.getBody().getData().add(item);
            }
        }

        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
            result.setCode(DtoConstants.SUCCESS,null);
        }
        return result;
    }

    @Route(value = {"/agent/relation/user/info.html"})
    public String user(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request, "userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(userId, relationUserId);
        if(agentRelation != null) {
        	WebUtils.setAttribute(request, agentRelation);
        	User user = UserService.self().getById(agentRelation.getUserId());
        	request.setAttribute("agent", user);
        	
        	AgentRelationDeviceSearch search1 = new AgentRelationDeviceSearch();
        	search1.setUserId(agentRelation.getUserId());
        	search1.setRelationUserId(agentRelation.getRelationUserId());
        	Long deviceCount = AgentRelationDeviceService.self().countJoinBySearch(search1);
        	request.setAttribute("deviceCount", deviceCount);
        	
            Long placeCount = PlaceProfitUserService.self().countByUserKeys(agentRelation.getUserId()
            		,agentRelation.getRelationUserId());
          	request.setAttribute("placeCount", placeCount);
        }
        return "/agent/relation/user.html";
    }
    
    @Route(value = "/agent/relation/user/device/list.data")
    public ListResult<AgentRelationDevice> deviceListData(HttpServletRequest request) {
        ListResult<AgentRelationDevice> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        List<AgentRelationDevice> data = AgentRelationDeviceService.self().findJoinByUserKeys(userId,relationUserId);
        if(data != null && data.size() > 0){
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(data);
        }
        return result;
    }
	
	@Route(value = "/agent/relation/user/place/list.data")
    public ListResult<AgentRelationPlace> placeListData(HttpServletRequest request) {
        ListResult<AgentRelationPlace> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        List<PlaceProfitUser> data = PlaceProfitUserService.self().findByUserKeys(userId,relationUserId);
        if(data != null && data.size() > 0){
        	result.setCode(DtoConstants.SUCCESS, null);
        	result.getBody().setData(new ArrayList<>());
        	List<Long> placeIds = new ArrayList<>();
        	for(PlaceProfitUser profitUser : data) {
        		placeIds.add(profitUser.getPlaceId());
        	}
        	List<PlacePhysicalStore> placeList = PlacePhysicalStoreService.self().findByIds(placeIds);
            
        	for(PlaceProfitUser profitUser : data) {
        		AgentRelationPlace item = new AgentRelationPlace();
        		item.setId(profitUser.getPlaceId());
        		item.setRoleTypeName(profitUser.getRoleTypeName());
        		item.setCreateDate(profitUser.getCreateDate());
        		
        		if(StringTools.isNotBlank(profitUser.getIncomeRatioContent())) {
        			IncomeRatioContent incomeRatioContent = JsonTools.fromJson(profitUser.getIncomeRatioContent(), IncomeRatioContent.class);
        			if(incomeRatioContent != null && incomeRatioContent.getItems() != null && incomeRatioContent.getItems().size() > 0) {
        				String temp = "";
        				for(IncomeRatioContent.Item incomeRatioItem : incomeRatioContent.getItems()) {
        					temp = temp + "," + EBusinessType.note(incomeRatioItem.getBusinessType()) + ":" + incomeRatioItem.getIncomeRatio()+"%";
        				}
        				item.setIncomeRatioNote(temp.substring(1));
        			}
        		}
        		
        		if(placeList != null && placeList.size() > 0) {
        			for(PlacePhysicalStore place : placeList) {
        				if(place.getId().equals(item.getId())) {
        					item.setName(place.getName());
        					item.setAreaName(place.getAreaName());
        					item.setTypeNames(place.getTypeNames());
        					break;
        				}
        			}
        		}
        		result.getBody().getData().add(item);
        	}
        }
        return result;
    }
    
    @Route(value = {"/agent/relation/user/role_type/update.html"})
    public String updateRoleType(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request, "userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(userId, relationUserId);
        if(agentRelation != null) {
        	WebUtils.setAttribute(request, agentRelation);
        }
        request.setAttribute("roleTypeList", AgentRelationEnum.RoleType.values());
        return "/agent/relation/edit_role_type.html";
    }
    
    @Route(value = { "/agent/relation/user/role_type/update.do" })
    public AjaxResult doUpdateRoleType(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        Integer roleType = WebUtils.getInteger(request, "roleType");
        try {
            if(AgentRelationService.self().updateRoleType(userId,relationUserId,roleType)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
    
    @Route(value = { "/agent/relation/user/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        try {
            if(AgentRelationService.self().deleteByKeys(userId,relationUserId)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = "/agent/relation/user/busi_config/list.data")
    public ListResult<AgentRelationBusinessConfig> busiConfigListData(HttpServletRequest request) {
        ListResult<AgentRelationBusinessConfig> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        List<AgentRelationBusinessConfig> data = AgentRelationBusinessConfigService.self().findByUserKeys(userId,relationUserId);
        if(data != null && data.size() > 0){
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(data);
        }
        return result;
    } 
    
    @Route(value = "/agent/relation/user/func_model/list.data")
    public ListResult<AgentRelationFuncModel> funcModelListData(HttpServletRequest request) {
        ListResult<AgentRelationFuncModel> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        List<AgentRelationFuncModel> data = AgentRelationFuncModelService.self().findJoinByUserKeys(userId,relationUserId);
        if(data != null && data.size() > 0){
        	String resDomain = WebConstants.getResDomain(request);
        	for(AgentRelationFuncModel item : data) {
        		if(StringTools.isNotBlank(item.getFuncModel().getIconUrl())) {
        			item.getFuncModel().setIconUrl(WebUtils.setHttpDomain(resDomain, item.getFuncModel().getIconUrl()));
        		}
        	}
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(data);
        }
        return result;
    }

    @Route(value = { "/agent/relation/user/func_model/add.html" })
    public String addFuncModel(HttpServletRequest request) {
    	Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        AgentRelation agentRelation = AgentRelationService.self().getByKeys(userId, relationUserId);
    	request.setAttribute("type", agentRelation.getRoleType());
        return "/agent/relation/func_model/edit.html";
    }

    @Route(value = { "/agent/relation/user/func_model/add.do" })
    public AjaxResult doAddFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        AgentRelationFuncModel funcModel = WebUtils.getParameter(request, AgentRelationFuncModel.class);
        try {
        	funcModel.setState(AgentRelationFuncModelEnum.State.Open.index());		//默认开启
            if(AgentRelationFuncModelService.self().add(funcModel)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/relation/user/func_model/del.do" })
    public AjaxResult doDelFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Long relationUserId = WebUtils.getLong(request,"relationUserId");
        Long funcModelId = WebUtils.getLong(request,"funcModelId");
        try {
            if(AgentRelationFuncModelService.self().deleteByKeys(userId,relationUserId,funcModelId)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
